'use strict';
const { verifyJwt, loginResponse } = require('auth-token')
exports.main = async (event, context) => {
	
	// 需登录才能访问
	const payload = verifyJwt(event.token)
	if (!payload) {
	  return loginResponse()
	}
	const currentUid = payload._id
	// 数据库连接
	const dbJQL = uniCloud.databaseForJQL({event, context})
	const bookCollection = dbJQL.collection('ume-notebook')

	// 业务逻辑
	switch (event.action) {
		case 'userRetrieve':
			// 查询当前本的列表
			const group = event.params.group
			const accList = await bookCollection.where(`group_id=='${group}' && user_id=='${currentUid}'`).get()
			// console.log("ledge:", ledger.data)
			return {
				data: accList.data,
				message: '查询成功!!'
			}
			break;
		case 'userCreate':
			const createData = event.create_data
			if (!createData.group_id || !createData.account || !createData.passkey) {
				return {
					_id: '',
					message: '创建失败,请输入完整数据！'
				}
			}
			const addRes = await bookCollection.add({
				group_id: createData.group_id,
				user_id: currentUid,
				account: createData.account,
				passkey: createData.passkey,
				note: createData.note
			})
			return {
				_id: addRes.id,
				message: '创建成功!'
			}
			break;
		case 'userUpdate':
			const updateData = event.save_data
			if (!updateData._id || !updateData.group_id || !updateData.account || !updateData.passkey) {
				return {
					_id: '',
					message: '创建失败,请输入完整数据！'
				}
			}
			const updateRes = await bookCollection.doc(updateData._id).update({
				account: updateData.account,
				passkey: updateData.passkey,
				note: updateData.note
			})
			return {
			  _id: updateRes._id,
			  message: '更新成功!'
			}
			break;
		case 'userDel':
			const deleteId = event._id
			if (!deleteId) {
			  return {
			    error: true,
			    message: '参数错误，无法定位条目!'
			  }
			}
			await bookCollection.doc(deleteId).remove()
			return {
			  _id: '',
			  message: '删除成功!'
			}
			break 
		default:
		  break;
	}
	return {}
};
